<template>
  <div class="azure-d-table">
    <div
      :style="{ padding: `${isShowHeader ? 10 : 0}px` }"
      class="chino-filter-wrap"
      v-if="isShowHeader"
    >
      <div style="width: 80%">
        <!--     style="display: flex;justify-content: center;align-items: center;flex-wrap: wrap"   div   -->
        <slot name="tableHead"></slot>
      </div>

      <el-popover
        class="popover"
        placement="bottom"
        trigger="click"
        v-show="isShowFilterColumnBtn"
      >
        <div class="filter-container" style="display: flex;flex-direction: column;">
          <el-col :span="24" style="margin-bottom: 10px">
            <el-checkbox
              :indeterminate="isIndeterminate"
              @change="handleCheckAllColumnChange"
              v-model="checkAll"
            >
              展示全部
            </el-checkbox>
          </el-col>
          <el-checkbox-group
            @change="handleCheckedChange"
            v-model="curCheckCols"
          >
            <div class="outer" style="display: flex; flex-direction: row;">
              <div :key="idx"
                   class="inner"
                   style="margin: 0 5px;"
                   v-for="(dynamicCols,idx) in  dynamicColsSplit"
              >
                <el-tooltip
                  :content="getLabelByKey(item)"
                  :open-delay="1000"
                  effect="dark"
                  style="margin: 2px 0;"
                  v-for="item in dynamicCols"
                >
                  <el-checkbox :label="item">
                    {{ getLabelByKey(item) }}
                  </el-checkbox>
                </el-tooltip>
              </div>
            </div>


          </el-checkbox-group>
        </div>
        <el-button icon="el-icon-s-operation" size="mini" slot="reference" type="primary" v-waves>
          <!--          <span style="position: relative;bottom: 3px;">筛选 </span>-->
          筛选
          <!--          <img alt="" src="./filter_icon.png"/>-->
        </el-button>
      </el-popover>
    </div>

    <div class="table-wrap">
      <el-table
        :border="border"
        :data="data"
        :header-cell-class-name="headerRowStyle"
        :key="tableKey"
        ref="azureTable"
        v-bind="$attrs"
        v-on="$listeners"
      >
        <!--  checkBox 按钮  -->
        <slot name="selection"></slot>

        <!--        <slot name="expand"></slot>-->

        <el-table-column
          align="center"
          label="序号"
          type="index"
          v-if="showSeq"
          width="70"
        >
        </el-table-column>

        <!--     展开行   -->
        <el-table-column type="expand" v-if="expand">
          <template slot-scope="scope">
            <slot :scope="scope" name="expand"></slot>
          </template>
        </el-table-column>

        <slot name="pre-column"/>

        <el-table-column
          :align="columnDes.align || 'center'"
          :fixed="isOperator(columnDes) ? 'right' : false"
          :header-align="columnDes.headerAlign"
          :key="columnDes.key"
          :label="columnDes.label"
          :prop="columnDes.key"
          :sortable="columnDes.sortable"
          :width="columnDes.width"
          v-for="columnDes in columnDesObjs"
          v-if="isShowCurCol(columnDes)"
        >
          <div
            :style="getColCellStyle(columnDes)"
            slot-scope="scope"
          >

            <slot :name="columnDes.key" :scope="scope">
              <!--                <el-image-->
              <!--                  v-if="columnDes.img"-->
              <!--                  :src="scope.row[columnDes.key]" fit="cover" style="-->
              <!--                      display: flex;align-items: center;justify-content: center;font-size: 17px;-->
              <!--                      width: 80px;height: 80px;border-radius: 3px">-->
              <!--                  <div class="image-slot" slot="error">-->
              <!--                    <i class="el-icon-picture-outline"></i>-->
              <!--                  </div>-->
              <!--                </el-image>-->
              <template v-if="columnDes.tag">
                <el-tag
                  :type="
                    columnDes.filter &&
                      columnDes.filter(scope.row[columnDes.key], tagStatusName)
                  "
                >
                  {{getTagValue(columnDes,scope) }}
                </el-tag>
              </template>

              <template v-else-if="columnDes.image">
                <!--  scope.row[columnDes.key] -->
                <el-image
                  :preview-src-list="[scope.row[columnDes.key]]"
                  :src="scope.row[columnDes.key]"
                  fit="cover"
                  style="width: 80px; height: 80px;border-radius: 5px"
                >
                  <!--<div slot="error" class="image-slot">-->
                  <!--<span>图片加载失败😂</span>-->
                  <!--&lt;!&ndash;<i class="el-icon-picture-outline"></i>&ndash;&gt;-->
                  <!--</div>-->
                </el-image>
              </template>

              <template v-else-if="columnDes.dateFormat">
                <i class="el-icon-time" style="margin-right: 10px"></i>
                <span>{{ dateFormat(scope.row[columnDes.key]) }}</span>
              </template>
              <template v-else-if="columnDes.filter">
                {{ columnDes.filter(scope.row[columnDes.key]) }}
              </template>
              <template v-else>
                {{ scope.row[columnDes.key] }}
              </template>
            </slot>
          </div>
        </el-table-column>

        <slot name="last-column"/>

        <div slot="append">
          <slot name="azure"></slot>
        </div>

      </el-table>
    </div>
  </div>
</template>

<script>
  import { dateFormat } from '@/utils/commons'
  import waves from '@/directive/waves'

  // class Column {
  //   label
  //   key
  //   isDefaultShowDynamicColumn
  //   width
  // }
  const MAX_SPLIT = 10

  export default {
    name: 'AzureDynamicTable',
    directives: { waves },
    props: {
      data: {
        type: Array, //  表格的元数据
        require: true
      },
      columnDesObjs: {
        type: Array,
        default: () => [
          {
            label: '用户名',
            key: 'userName',
            isDefaultShowDynamicColumn: false,
            width: ''
          }
        ]
      },

      operatorColWidth: {
        type: Number,
        default: 250
      },
      operatorObjs: {
        type: Array,
        default: () => []
      },
      tagStatusName: {
        type: String,
        default: 'status'
      },
      showSeq: {
        type: Boolean,
        default: false
      },
      isShowHeader: {
        type: Boolean,
        default: true
      },
      expand: {
        type: Boolean,
        default: false
      },
      border: {
        type: Boolean,
        default: false
      },
      headerColor: {
        type: Boolean,
        default: true
      },
      filterMax: {
        type: Number,
        default: MAX_SPLIT
      }
    },
    data() {
      return {
        curCheckCols: this.columnDesObjs
          .filter(e => e.isDefaultShowDynamicColumn)
          .map(e => e.key), // 当前勾选的动态列
        dynamicCols: [], // 全部的动态列
        // defShowDynamicCols: [], // 默认显示的动态列

        tableKey: 3,
        checkAll: false,
        isIndeterminate: false
      }
    },
    mounted() {
      // console.log(this.curCheckCols)
      this.handleCheckedChange(this.curCheckCols)
    },
    computed: {
      dynamicColsSplit() {
        return Array.from({ length: Math.ceil(this.dynamicCols.length / this.filterMax) })
          .reduce((acc, _, idx) =>
              Array.of(...acc, this.dynamicCols.slice(idx * this.filterMax, (idx + 1) * this.filterMax))
            , Array.of())
      },
      isShowFilterColumnBtn() {
        return this.columnDesObjs.some(e => {
          return e.isDefaultShowDynamicColumn !== undefined
        })
      }
      // constCols() {
      //     const allCols = this.data.map(e => e.key);
      //     return this.dynamicCols.filter((e) => {
      //         return !allCols.includes(e)
      //     })
      // }
    },
    methods: {
      getTagValue(columnDes, scope) {

        // columnDes.filter
        // ? columnDes.filter(scope.row[columnDes.key])
        // : scope.row[columnDes.key]

        const res = columnDes.filter
          ? columnDes.filter(scope.row[columnDes.key])
          : scope.row[columnDes.key]
        return res ? res : '―'
      },
      getColCellStyle(columnDes) {
        const { cellWrapNotCenter } = columnDes
        if (cellWrapNotCenter) {
          if (typeof cellWrapNotCenter === 'string') {
            return cellWrapNotCenter
          }
          return ''
        } else {
          return 'display: flex;justify-content: center;align-items: center'
        }
      },

      clearSort() {
        this.$refs.azureTable.clearSort()
      },
      clearMultiSelected() {
        this.$refs.azureTable.clearSelection()
      },

      /**
       *
       * @param value 列的id值
       * @param propKey 根据表格列key来判断
       */
      setCurrentRowBy({ value, propKey = 'id' }) {
        const hasColKey = this.columnDesObjs.some(({ key }) => key === propKey)
        !hasColKey && console.warn(
          `setCurrentRowBy 没有找到当前列属性 ${propKey} ,可能会导致运行不正确,检查表格 columnDesObjs 中是否有key为 ${propKey} 的列描述定义`)

        this.$refs.azureTable.setCurrentRow(this.data.find(v => v[propKey] === value))
      },

      setCurrentRow(row) {
        console.log(' setCurrentRow proxy by azureDynamic table >>>>>>>>>>>')
        this.$refs.azureTable.setCurrentRow(row)
      },

      getLabelByKey(key) {
        //  没有就返回英文
        const ret = this.columnDesObjs.find(e => e.key === key)
        // console.log(ret);
        return ret ? ret.label : key
      },

      dateFormat,
      isOperator(columnDes) {
        return columnDes.key === 'operator'
      },
      handleCheckedChange(val) {
        // console.log(val)
        const checkedCount = val.length
        this.checkAll = checkedCount === this.dynamicCols.length
        this.isIndeterminate =
          checkedCount > 0 && checkedCount < this.dynamicCols.length
      },
      handleCheckAllColumnChange(val) {
        this.curCheckCols = val ? this.dynamicCols : []
        this.isIndeterminate = false
      },
      isShowCurCol(columnDes) {
        if (this.dynamicCols.includes(columnDes.key)) {
          return this.curCheckCols.includes(columnDes.key) //  动态列
        } else {
          return true //  默认显示非动态列
        }
        // console.warn(`列问题 => ${columnDes} row => ${JSON.stringify(row)}`);
      },
      headerRowStyle({ row }) {
        return this.headerColor ? 'azure-d-table-h-header' : ''
      }
    },

    watch: {
      columnDesObjs: {
        immediate: true,
        deep: true,
        handler(newVal, oldVal) {
          this.dynamicCols = newVal
            .filter(e => e.isDefaultShowDynamicColumn !== undefined)
            .map(e => e.key)
          // this.defShowDynamicCols = newVal.filter(e => e.isDefaultShowDynamicColumn === true)
        }
      },
      curCheckCols: {
        deep: true,
        handler(valArr) {
          // this.dynamicCol = this.formTheadOptions.filter(i => valArr.indexOf(i) >= 0)
          ++this.tableKey
        }
      }
    }
  }
</script>

<style>
  .azure-d-table-h-header {
    background: #f3f6ff !important;
    height: 50px !important;
  }

  .el-checkbox {
    display: flex;
    align-items: center;
  }

  .el-checkbox__label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100px;
  }
</style>

<style lang="scss" scoped>
  @import "~@/assets/css/gloabal.scss";

  .azure-d-table {
    background: $whiteColor;

    .chino-filter-wrap {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 10px;
      align-items: center;
      /*margin-bottom: 10px;*/
    }

    /*.table-wrap {*/
    /*  position: relative;*/

    /*  .popover {*/
    /*    position: absolute;*/
    /*    z-index: 100;*/
    /*    right: 3px;*/
    /*    top: 7px;*/
    /*  }*/
    /*}*/
  }
</style>
